﻿@page "/FunctionPageManger"

<Table TItem="FunctionPage"
       IsPagination="true" PageItemsSource="new int[]{20,10,30}"
       IsStriped="true" IsBordered="true" IsMultipleSelect="true"
       IsExtendButtonsInRowHeader="false"
       ShowToolbar="true" ShowExtendButtons="true" ShowSkeleton="true"
       OnQueryAsync="@OnQueryAsync"
       OnAddAsync="@OnAddAsync"
       OnSaveAsync="@OnSaveAsync"
       OnDeleteAsync="@OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.Name" />
        <TableColumn @bind-Field="@context.Icon" />
        <TableColumn @bind-Field="@context.PageType"   />
        <TableColumn @bind-Field="@context.ShowMsgType"   />
    </TableColumns>
    <BeforeRowButtonTemplate Context="value">
        <TableCellButton OnClick="()=>{OnClick(value.Id);}">编辑权限</TableCellButton>
    </BeforeRowButtonTemplate>
</Table>

@code {
    [Inject]
    [NotNull]
    public ISqlSugarClient? db { get; set; }
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }
    protected override Task OnInitializedAsync()
    {

        return base.OnInitializedAsync();
    }
    public void OnClick(long id)
    {
        DialogService.ShowModal<FunctionPageAddRole>(new ResultDialogOption()
            {
                ComponentParameters = new Dictionary<string, object>
                {
                    [nameof(FunctionPageAddRole.Id)] = id,
                }
            });
    }
    private Task<FunctionPage> OnAddAsync()
    {
        return Task.FromResult(new FunctionPage() {  MainPage=new MainPage()});
    }

    private async Task<QueryData<FunctionPage>> OnQueryAsync(QueryPageOptions options)
    {
        var item = await db.Queryable<FunctionPage>().ToListAsync();
        return new QueryData<FunctionPage>()
            {
                Items = item,
                TotalCount = item.Count,
            };
    }
    private async Task<bool> OnDeleteAsync(IEnumerable<FunctionPage> items)
    {
        var res = await db.Deleteable<FunctionPage>(items).ExecuteCommandAsync();
        return res > 0 ? true : false;
    }
    private async Task<bool> OnSaveAsync(FunctionPage item, ItemChangedType changedType)
    {
        if (changedType == ItemChangedType.Add)
        {
            var id = db.Queryable<Role>().First(x => x.Name == "admin").Id;
            item.Roles = new List<Role>() { new Role() { Id = id } };
            List<FunctionPage> List = new List<FunctionPage> { item };
            db.InsertNav(List)
                       .Include(z1 => z1.Roles)
                       .ExecuteCommand();
            // await db.Insertable(item).ExecuteReturnSnowflakeIdAsync();
        }
        else
        {
            await db.Updateable(item).ExecuteCommandAsync();
        }
        return true;
    }
}

